package cn.fl.mcr.controller;

import cmm.comm.facade.upload.constant.SysUlFilesRecConstant;
import cmm.mid.core.framework.dto.DataResultDTO;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.mcr.service.IMcrContractService;
import cn.fl.mcr.vo.McrBillMVO;
import cn.fl.spl.utils.FileUtil;
import cn.lionbridgecapital.loan.model.base.Pager;
import cn.lionbridgecapital.loan.model.condition.McrBillMQC;
import cn.lionbridgecapital.loan.model.utils.StringUtils;
import cn.lionbridgecapital.loan.service.api.IMcrBillMApiService;
import cn.lionbridgecapital.loan.service.api.IMcrContractApiService;
import cn.lionbridgecapital.loan.utils.BaseLogUtils;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: YangXin
 * @Description: 小贷合同Controller
 * @CreateTime: 2019/12/11 11:34
 * @Version: 1.0.0
 */
@RestController
@RequestMapping("/mcr/contract")
public class McrContractController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(McrContractController.class);

    @Autowired
    private IMcrContractApiService publicMcrContractApiService;
    @Autowired
    private IMcrBillMApiService publicMcrBillMApiService;
    @Autowired
    private IMcrContractService mcrContractService;

    @RequestMapping("/toMcrContractList.do")
    public ModelAndView toMcrContractList(HttpServletRequest request, HttpServletResponse response){
        final String methodName = "toMcrContractList";
        ModelAndView modelAndView = new ModelAndView("mcr/mcrContract/mcrContractList");
        BaseLogUtils.info(logger,methodName,"跳转至小贷合同页面");
        return modelAndView;
    }

    @RequestMapping(value = "/additionalContract.do",method = RequestMethod.POST)
    public DataResultVO additionalContract(HttpServletRequest request, HttpServletResponse response){
        final String methodName = "additionalContract";
        DataResultVO resultVO = new DataResultVO(BaseConstant.IS_YESNO_NO, "合同补录失败");

        String cstId = request.getParameter("cstId");
        String contract = request.getParameter("contract");
        String contractType = request.getParameter("contractType");
        if (StringUtils.isEmpty(cstId)){
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("客户Id为空");
            return resultVO;
        }
        if (StringUtils.isEmpty(contract)){
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("合同号为空");
            return resultVO;
        }

        try{
            DataResultDTO resultDTO = this.publicMcrContractApiService.additionalContract(Long.parseLong(cstId), contract, contractType);
            BaseLogUtils.info(logger,methodName,"小贷系统补录合同.结果："+ JSONObject.toJSONString(resultDTO));
            if (null != resultDTO && BaseConstant.IS_YESNO_YES == resultDTO.getSuccess()){
                resultVO.setSuccess(BaseConstant.IS_YESNO_YES);
                resultVO.setInfo("电子合同补录成功");
            }
        }catch (BaseException ex){
            BaseLogUtils.error(logger,methodName,"小贷系统补录合同.异常："+ex.getMessage(),ex);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo(ex.getMessage());
        }catch (Exception ex){
            BaseLogUtils.error(logger,methodName,"小贷系统补录合同.异常："+ex.getMessage(),ex);
            resultVO.setSuccess(BaseConstant.IS_YESNO_NO);
            resultVO.setInfo("补录合同异常");
        }
        BaseLogUtils.info(logger,methodName,"小贷系统补录合同.返回前端结果："+ JSONObject.toJSONString(resultVO));
        return resultVO;
    }

    /**
     * 初始化列表
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/initList.do", method = {RequestMethod.GET,RequestMethod.POST})
    public Object initMcrBillMList(HttpServletRequest request, HttpServletResponse response) {
        final String methodName = "initMcrBillMList";
        String currentPage = request.getParameter("page");
        String pageSize = request.getParameter("pagesize");
        Pager page = new Pager();
        if (StringUtils.isNotEmpty(currentPage)) {
            page.setCurrentPage(Integer.parseInt(currentPage));
        }
        if (StringUtils.isNotEmpty(pageSize)) {
            page.setEveryPage(Integer.parseInt(pageSize));
        }

        String cstId = request.getParameter("cstId");
        String contract = request.getParameter("contract");

        McrBillMQC qc = new McrBillMQC();
        if (StringUtils.isNotEmpty(cstId)) {
            qc.setCstId(Long.parseLong(cstId));
        }
        if (StringUtils.isNotEmpty(contract)) {
            qc.setCrCntNo(contract);
        }

        List<String> loanStsCdList = new ArrayList<>();
        loanStsCdList.add("4");
        loanStsCdList.add("6");
        loanStsCdList.add("7");

        qc.setIsDel(BaseConstant.IS_YESNO_NO);
        qc.setLoanStsCdList(loanStsCdList);
        page.setCondition(qc);
        ListPageVO<McrBillMVO> listPage = null;
        try {
            Pager pager = this.mcrContractService.searchMcrBillMListPage(page);
            List<McrBillMVO> list = (List<McrBillMVO>) pager.getResultList();
            listPage = new ListPageVO<>(list, pager.getTotalCount());
        } catch (BaseException ex){
            BaseLogUtils.error(logger, methodName, "小贷合同管理.获取账单主表业务异常" + ex.getMessage(),ex);
        }catch (Exception ex){
            BaseLogUtils.error(logger, methodName, "小贷合同管理.获取账单主表异常" + ex.getMessage(),ex);
        }
        return listPage;
    }

    @RequestMapping(value = "/importData.do", method = {RequestMethod.POST,RequestMethod.GET})
    public DataResultVO importData(HttpServletRequest request, HttpServletResponse response) throws IOException {
        final String methodName = "importData";
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, methodName, "导入Excel补录仲裁合同.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, "补录仲裁合同成功");
        String filePath = request.getParameter("filePath");//文件路径
        String arbitrateType = request.getParameter("arbitrateType"); // 1.跳过已经存在 0.作废旧合同生成新合同
        try {
            String rootPath = PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH);
            String realPath = rootPath + filePath;
            DataResultDTO resultDTO = this.mcrContractService.importData(realPath,arbitrateType);
            BaseLogUtils.info(logger, methodName, "导入Excel补录仲裁合同.返回参数：" +JSONObject.toJSONString(resultDTO), CurrentThreadContext.getCurrentUserName());
            if (BaseConstant.IS_YESNO_YES != resultDTO.getSuccess()){
                result.setSuccess(BaseConstant.IS_YESNO_NO);
                result.setInfo(resultDTO.getInfo());
            }

        } catch (BaseException ex) {
            BaseLogUtils.error(logger, methodName, "导入Excel补录仲裁合同.异常", CurrentThreadContext.getCurrentUserName(), ex);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo(ex.getMessage());
        } catch (Exception e) {
            BaseLogUtils.error(logger, methodName, "导入Excel补录仲裁合同.异常", CurrentThreadContext.getCurrentUserName(), e);
            result.setSuccess(BaseConstant.IS_YESNO_NO);
            result.setInfo("导入Excel补录仲裁合同失败");
        }
        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, methodName, "导入Excel补录仲裁合同.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        BaseLogUtils.info(logger, methodName, "导入Excel补录仲裁合同.返回结果：" + JSONObject.toJSONString(result), CurrentThreadContext.getCurrentUserName());
        return result;
    }

    /**
     * 下载模板
     */
    @RequestMapping(value = "/download.do", method = {RequestMethod.POST})
    @ResponseBody
    public DataResultVO download(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "download", "下载模板" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        DataResultVO vo =new DataResultVO(BaseConstant.IS_YESNO_YES,"模板获取成功");
        String tempPath= FileUtil.getSavePath("template/mcr/mcrContractTemplate.xlsx");
        tempPath = tempPath.replace(
                PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_ROOT_PATH),
                PropertiesCacheUtils.getProperty(SysUlFilesRecConstant.SYS_FILE_UPLOAD_SERVER_PATH));
        Long endTm = System.currentTimeMillis();
        vo.setData(tempPath);
        BaseLogUtils.info(logger, "download", " 下载模板.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        BaseLogUtils.info(logger, "download", " 下载模板.返回结果：" + tempPath, CurrentThreadContext.getCurrentUserName());
        return vo;
    }

    /**
     * 到补录仲裁合同Excel导入页面
     */
    @RequestMapping(value = "/toMcrArbitrateContract.do", method = {RequestMethod.GET})
    public ModelAndView toMcrArbitrateContract(HttpServletRequest request, HttpServletResponse response) {
        Long startTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toMcrArbitrateContract", "加载到补录仲裁合同Excel导入页面.请求参数：" + this.getRequestParameter(request), CurrentThreadContext.getCurrentUserName());
        String arbitrateType = request.getParameter("arbitrateType");
        ModelAndView view = new ModelAndView("mcr/mcrContract/mcrArbitrateContract");
        view.addObject("arbitrateType",arbitrateType);

        Long endTm = System.currentTimeMillis();
        BaseLogUtils.info(logger, "toMcrArbitrateContract", "加载到补录仲裁合同Excel导入页面.耗时：" + (endTm - startTm), CurrentThreadContext.getCurrentUserName());
        return view;
    }
}
